/**
 * Created by Administrator on 2019/1/7.
 */

package com.game.fg.service;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft_6455;
import org.java_websocket.handshake.ServerHandshake;
import org.json.JSONObject;

import java.net.URI;
import java.net.URISyntaxException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;

class MQServer {

    private WebSocketClient ws;
    private static Logger logger = LogManager.getLogger(MQServer.class.getName());

    public WebSocketClient getWs() {
        return ws;
    }

    void start(String url) {
        try {
            ws = new WebSocketClient(new URI(url), new Draft_6455()) {
                @Override
                public void onMessage(String message) {
                    logger.debug("MQ服务器 onMessage(String message)");
                }

                @Override
                public void onMessage(ByteBuffer blob) {
                }

                @Override
                public void onOpen(ServerHandshake handshake) {
                    logger.debug("MQ服务器连接成功");
                }

                @Override
                public void onClose(int code, String reason, boolean remote) {
                    logger.debug("MQ服务器连接断开");
                }

                @Override
                public void onError(Exception ex) {
                    ex.printStackTrace();
                }
            };
            ws.connect();
        } catch (URISyntaxException ex) {
            ex.printStackTrace();
        }
    }

    //心跳包
    void KeepAlive() {
        if (ws.isOpen()) {
            FGWebSocket.sendCustom(ws, FGConst.CMD_KEEP_ALIVE, new byte[]{});
        }
    }

    //当玩家进入游戏
    void onUserLogin(FGUser user) {
        JSONObject jsonContent = new JSONObject();
        jsonContent.put("event", "game_login");
        jsonContent.put("idevent", 1008);
        jsonContent.put("gameid", ManagerServer.serverInfo.gameID);
        jsonContent.put("levelgame", 0);
        jsonContent.put("roomid", 0);
        jsonContent.put("areaid", 10);
        jsonContent.put("channelid", 20154);
        jsonContent.put("distinct_id", 30121);
        jsonContent.put("saved_field", 0);
        jsonContent.put("userlcid", "5221000001116000");
        JSONObject jsonProperties = new JSONObject();
        jsonProperties.put("gamecoin", user.getMoney());
        jsonProperties.put("gamename", "猜拳");
        jsonProperties.put("time", System.currentTimeMillis() / 1000);
        jsonContent.put("properties", jsonProperties.toString());
        SendLog(user.getUid(), FGConst.EVENT_GameLogin, "游戏玩家登录", jsonContent.toString());
    }

    //当玩家离开游戏
    void onUserLeave(FGUser user) {
        JSONObject jsonContent = new JSONObject();
        jsonContent.put("event", "game_leave");
        jsonContent.put("idevent", 1009);
        jsonContent.put("gameid", ManagerServer.serverInfo.gameID);
        jsonContent.put("levelgame", 0);
        jsonContent.put("roomid", 0);
        jsonContent.put("areaid", 10);
        jsonContent.put("channelid", 20154);
        jsonContent.put("distinct_id", 30121);
        jsonContent.put("saved_field", 0);
        jsonContent.put("userlcid", "5221000001116000");
        JSONObject jsonProperties = new JSONObject();
        jsonProperties.put("gamecoin", user.getMoney());
        jsonProperties.put("gamename", "猜拳");
        jsonProperties.put("time", System.currentTimeMillis() / 1000);
        jsonContent.put("properties", jsonProperties.toString());
        SendLog(user.getUid(), FGConst.EVENT_GameLeave, "游戏玩家离开", jsonContent.toString());
    }

    //玩家金币变化
    void onMoneyChange(FGUser user, int changeMoney, int optSrc) {
        JSONObject jsonContent = new JSONObject();
        jsonContent.put("event", "gamecoin_writedb");
        jsonContent.put("idevent", 1010);
        jsonContent.put("gameid", ManagerServer.serverInfo.gameID);
        jsonContent.put("levelgame", 0);
        jsonContent.put("roomid", 0);
        jsonContent.put("areaid", 10);
        jsonContent.put("channelid", 20154);
        jsonContent.put("distinct_id", 30121);
        jsonContent.put("saved_field", 0);
        jsonContent.put("userlcid", "5221000001116000");
        JSONObject jsonProperties = new JSONObject();
        jsonProperties.put("coinsourceid", optSrc);
        jsonProperties.put("changecoin", changeMoney);
        jsonProperties.put("time", System.currentTimeMillis() / 1000);
        jsonContent.put("properties", jsonProperties.toString());
        SendLog(user.getUid(), FGConst.EVENT_GameCoinWriteDb, "写分日志", jsonContent.toString());
    }

    //救济金消耗
    void onConsumeBenefits(FGUser user, int consume) {
        JSONObject jsonContent = new JSONObject();
        jsonContent.put("event", "consume_helpcoin_log");
        jsonContent.put("idevent", 1011);
        jsonContent.put("gameid", ManagerServer.serverInfo.gameID);
        jsonContent.put("levelgame", 0);
        jsonContent.put("roomid", 0);
        jsonContent.put("areaid", 10);
        jsonContent.put("channelid", 20154);
        jsonContent.put("distinct_id", 30121);
        jsonContent.put("saved_field", 0);
        jsonContent.put("userlcid", "5221000001116000");
        JSONObject jsonProperties = new JSONObject();
        jsonProperties.put("consumecoin", consume);
        jsonProperties.put("time", System.currentTimeMillis() / 1000);
        jsonContent.put("properties", jsonProperties.toString());
        SendLog(user.getUid(), FGConst.EVENT_ConsumeHelpCoin, "共济金消耗日志", jsonContent.toString());
    }

    //向MQ服务器写日志
    private void SendLog(int userId, short eventId, String eventName, String content) {
        if (ws == null || ws.isClosed()) {
            return;
        }
        ByteBuffer bb = ByteBuffer.allocate(760);
        bb.order(ByteOrder.LITTLE_ENDIAN);

        bb.putShort(ManagerServer.serverInfo.gameID);
        bb.putShort(ManagerServer.serverInfo.serverID);
        bb.putShort(eventId);//usEventID
        bb.putShort((short) 1);//usGameLevel

        bb.putInt(userId);
        bb.putInt(0);//iChannelID
        bb.putInt(0);//iSiteID
        byte[] acMqEName = new byte[32];
        System.arraycopy(eventName.getBytes(), 0, acMqEName, 0, eventName.length());
        byte[] acMqExtand = new byte[40];
        bb.put(acMqEName);//acMqEName
        bb.put(acMqExtand);//acMqExtand
        bb.putInt(0);//uiUniKey
        byte[] acChannelID = new byte[20];
        bb.put(acChannelID);//acChannelID
        byte[] acMqContent = new byte[644];
        System.arraycopy(content.getBytes(), 0, acMqContent, 0, content.length());
        bb.put(acMqContent);//acMqContent
        FGWebSocket.sendCustom(ws, 0X1000, bb.array());

    }

    private MQServer() {
    }

    private static MQServer ms = new MQServer();

    public static MQServer getInstance() {
        return ms;
    }
}
